package com.example.tests;


import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import ru.esteru.selenium.factory.WebDriverFactory;

public class AddNewFilmFromIMDbTest {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	
	@Before
	public void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}
	
	@Test
	public void testAddNewFilmFromIMDb() throws Exception {
		goToMainPage();
		loginAs("admin", "admin");		
		searchMovieInIMDb("Midnight Madness");
		assertTrue("Movie don't added", isMovieAddedFromIMDb());
		addMovie();
		assertTrue("Movie don't save", isMovieSuccessfullySaved());
		deleteAddedMovie();
		logout();
	}
	
	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
	}

	private void loginAs(String username, String password) {
		driver.findElement(By.id("username")).clear();
		driver.findElement(By.id("username")).sendKeys(username);
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys(password);
		driver.findElement(By.name("submit")).click();
	}
	
	private void searchMovieInIMDb(String filmTitle) {
		driver.findElement(By.cssSelector("img[alt=\"Add movie\"]")).click();
		driver.findElement(By.id("imdbsearch")).clear();
		driver.findElement(By.id("imdbsearch")).sendKeys(filmTitle);
		driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
		driver.findElement(By.linkText(filmTitle)).click();	
	}
	
     private boolean isMovieAddedFromIMDb() {
		
		return driver.findElement(By.className("addmovie"))
				.findElement(By.tagName("h2")).getText().equals("Movie information");
     }
     
    private void addMovie() {
		
		driver.findElement(By.id("submit")).click();
	}
	
    private boolean isMovieSuccessfullySaved() {
	
	return driver.findElement(By.id("movie")).isDisplayed();
    }
    
	private void deleteAddedMovie() {
		driver.findElement(By.cssSelector("img[alt=\"Remove\"]")).click();
		driver.switchTo().alert().accept();
	}
	
   
	private void logout() {
		driver.findElement(By.linkText("Log out")).click();
		driver.switchTo().alert().accept();
	}
		
	@After
	public void tearDown() throws Exception {
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
	}